import random
import re
from Tag import Tag
from Connection import Connection

class Logic():
	def __init__(self):
		self.responses = []

	def findAnswer(self, text):
		responses = []
		logic = Logic()
		subber = re.compile(r"[^A-Za-z0-9]").sub
		for word in text.split(" "):
			word = subber("", word)
			word = word.lower()
			query = Tag.gql("WHERE text = :1", word)
			tag = query.get()
			if tag:
				query = Connection.gql("WHERE tag = :1", tag)
				connections = query.fetch(1000, 0)
				self.addResponses(connections)

	def addResponses(self, connections):
		for connection in connections:
			new = True
			for item in self.responses:
				if item.text == connection.response.text:
					item.value += connection.response.value
					new = False
			if new:
				self.responses.append(connection.response)

	def answerPresent(self):
		if len(self.responses) > 0:
			return True
		return False

	def getAnswer(self):
		count = 0;
		for response in self.responses:
			count += response.value
		number = random.randint(0, count)
		for response in self.responses:
			number -= response.value
			if number <= 0:
				return response.text
		return self.responses[0].text


